package com.kinglumi.ailighting.auth.login;

import com.alibaba.fastjson.JSON;
import com.kinglumi.ailighting.auth.bo.AccessToken;
import com.kinglumi.ailighting.auth.bo.ApiResult;
import com.kinglumi.ailighting.auth.cache.Cache;
import com.kinglumi.ailighting.auth.constant.CacheName;
import com.kinglumi.ailighting.auth.entity.UserDetail;
import com.kinglumi.ailighting.auth.entity.UserInfo;
import com.kinglumi.ailighting.auth.provider.JwtProvider;
import com.kinglumi.ailighting.auth.service.biz.UserInfoService;
import com.kinglumi.ailighting.auth.util.IpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

/**
 * @author Lxin
 * @version 1.0
 * @date 2021/8/10 15:34
 */
@Component
public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private Cache caffeineCache;

    @Autowired
    private JwtProvider jwtProvider;

    @Autowired
    private UserInfoService userService;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
//        response.getWriter().write( objectMapper.writeValueAsString(authentication));
        // 3 保存认证信息
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 4 生成自定义token
        AccessToken accessToken = jwtProvider.createToken((UserDetails) authentication.getPrincipal());

        UserDetail userDetail = (UserDetail) authentication.getPrincipal();
        userDetail.setUseToken(accessToken.getToken().replace("AI_Lighting-", ""));
        // 放入缓存
        accessToken.setNickname(userDetail.getUserInfo().getNickname());
        accessToken.setUserInfo(userDetail.getUserInfo());
        caffeineCache.put(CacheName.USER, userDetail.getUsername(), userDetail);
        ApiResult ok = ApiResult.ok(accessToken);
        setIp(request, userDetail.getUsername());
        writer.write(JSON.toJSONString(ok));
    }

    private void setIp(HttpServletRequest request, String username) {
        // 根据用户名验证用户
        UserInfo info1 = new UserInfo();
        info1.setUsername(username);
        UserInfo userInfo = userService.selectOne(info1);
        if (null == userInfo) {
            throw new UsernameNotFoundException("Login failed because username does not exist.");
        }
        String ipAddr = IpUtils.getIpAddr(request);
        userInfo.setLastIp(ipAddr);
        userInfo.setLastLoginTime(new Date());
        userService.updateSelectiveById(userInfo);
    }
}